/** ---------- 地图初始化 和 图层渲染 mixin  FOR Hmap 海康 （空间信息服务平台3.1） ---------- */
import {createApp} from 'vue'
// import { ajaxCtx } from '@/api/config.js'
import MapMarker from '@/components/map/overflow/MapMarker.vue' // 标记
const MyMapMarker =createApp(MapMarker)
let MAP_INSTANCE = null // 地图实例
const MAP_S3M = { // 图层：s3m
  osgbLayer: null, // osgbLayer图层
  drawLayer: null, // drawLayer图层 for pick polygons
  labelLayer: null, // 标签图层
  pickEvent: false
}
const MAP_LAYERS = {} // { [layerName]: { type: 1, layer: xx, doms: [], level: 2 } } // type(1:Vector  2:Overlay); VECTOR无doms
const MAP_DEFAULT_LEVEL = 2 // 默认覆盖物（清除）级别
export default {
  data () {
    return {
      mapIsReady: false // 地图是否准备就绪
    }
  },
  methods: {
    // ********** 地图 初始化&事件&通用方法 **********
    /**
     * 初始化地图
     * @param {String} sid dom id
     * @param {Object} config 配置参数
     * @param {Array} config.center 中心点 [lng, lat, 0]
     * @param {Number} config.zoom 层级
     * @param {String} config.crs 坐标系，默认4326
     * @param {Object} initLayer 初始化图层
     * @param {Object} initLayer.vector 矢量切片图层
     * @param {Object} initLayer.tms tms图层
     */
    mapInit (sid, config, initLayer) {
      // **** new hmap
      if (!config) { config = {} }
      const mapOptions = Object.assign({
        zoom: 13,
        maxLevel: 17,
        minLevel: 11,
        zoomInterval: 1, //地图级别改变一级时，需要滚轮滚动的次数
        // pitch:60,
        crs: new hmap.proj.Crs('4326'),
        center: new hmap.basetype.Coordinate(113.228348, 25.865742, 0),
      }, config)
      console.log('>>>>>>>>>> mapOptions：', mapOptions)
      MAP_INSTANCE = new hmap.Map(sid, mapOptions, () => {
        this.mapIsReady = true // 地图准备就绪
        // **** 矢量切片图层
        if (initLayer && initLayer.vector) {
          // initLayer.vector = { hvtUrl: ajaxCtx.hmap + '/hmap-server/hvt/', vOptions: { styleUrl: '', matrixOrigin: [-180, 90] }, layerName: '', zIndex:  }
          // 矢量切片图层 参数
          const vOptions = Object.assign({
            matrixOrigin: new hmap.basetype.Coordinate(-180, 90), // 切片原点
            dataFormat: 'hvt', // 切片格式
            labelOn: true, // 是否显示文字标注
            styleUrl: '', // './static/lib/hmap/style/white/mapStyle.json'
            isRTE: true
          }, initLayer.vector.vOptions)
          if (initLayer.vector.vOptions?.matrixOrigin) {
            vOptions.matrixOrigin = new hmap.basetype.Coordinate(initLayer.vector.vOptions.matrixOrigin[0], initLayer.vector.vOptions.matrixOrigin[1])
          }
          // console.log('>>>>>>>>>> vector vOptions：', vOptions)
          const vectilelayer = new hmap.layer.VectorTileLayer(initLayer.vector.layerName ?? '矢量切片图层', initLayer.vector.hvtUrl, vOptions)
          MAP_INSTANCE.addLayer(vectilelayer, initLayer.vector.zIndex ?? 0)
        }
        // **** TMS图层
        if (initLayer && initLayer.tms) {
          // initLayer.tms = { tmsUrl: '', vOptions: { matrixOrigin: [-180, 90] }, layerName: '', zIndex:  }
          const vOptions = Object.assign({
            matrixOrigin: new hmap.basetype.Coordinate(-180, 90),
            dataFormat: 'png',
            dataMaxLevel: 18
          }, initLayer.tms.vOptions)
          if (initLayer.tms.vOptions?.matrixOrigin) {
            vOptions.matrixOrigin = new hmap.basetype.Coordinate(initLayer.tms.vOptions.matrixOrigin[0], initLayer.tms.vOptions.matrixOrigin[1])
          }
          // console.log('>>>>>>>>>> tms vOptions：', vOptions)
          const tileLayer = new hmap.layer.TMSLayer(initLayer.tms.layerName ?? 'TMS图层', initLayer.tms.tmsUrl, vOptions)
          MAP_INSTANCE.addLayer(tileLayer, initLayer.tms.zIndex ?? 0) // 添加TMS图层并将图层z-index设置为0
        }
        /* 用户自定义回调 */
        if (config.callback) {
          config.callback(MAP_INSTANCE)
        }
        // MAP_INSTANCE.setHighlightColor(new hmap.style.Color(255, 0, 0, 0.4)) // 单体化  拾取-颜色
        // MAP_INSTANCE.setDepthMode(1) // 设置地图高深度模式
        // MAP_INSTANCE.rotate('pitch', 30)
        // MAP_INSTANCE.rotate('bearing', 98)
        // MAP_INSTANCE.addControl(new hmap.control.ScaleBar())
        // MAP_INSTANCE.addControl(new hmap.control.MousePosition())
        // 定义地图事件
        // this.mapEvents()
      })
    },

    // ********** 地图 事件/交互 相关函数 **********
    // 地图事件
    mapEvents () {
      if (MAP_INSTANCE) {
        MAP_INSTANCE.event.register(EventType.MAPMOUSEEVENT_CLICK, (event) => {
          // console.log('经纬度：', `${event.lonlat._x},${event.lonlat._y},${event.lonlat._z}`)
          // s3m拾取事件
          if (MAP_S3M.pickEvent) {
            this.mapS3MPick(event)
          }
        })
      }
    },
    // 设置层级
    mapSetZoom (val) {
      // MAP_INSTANCE.setZoom(val)
    },
    // 设置中心点
    mapSetCenter (val) {
    },
    // 获取纬度的偏移 （为中心点服务）
    getCenterLatIns (ins) {
      // if (ins === undefined || ins == null) { ins = 0.2 }
      // const bounds = MAP_INSTANCE.getBounds()
      // return (bounds.northEast.lat - bounds.southWest.lat) * ins
    },

    // ********** 地图 图层相关函数 **********
    /**
     * [000050] s3m三维地图
     * @param {Object} data 数据
     * @param {String} data.s3mUrl s3m配置文件地址 see ajaxCtx.s3m
     * @param {Object} data.labelOptions icon & textSymbol 标签配置数据 (为null则不用icon/textSymbol, 启用默认icon/textSymbol则为{})
     * @param {Boolean} data.pick 是否需要拾取
     * @param {Array} data.highlightColor 高亮颜色(拾取)for 拾取  [255, 0, 0, 0.4]
     * @param {Array} data.list 标签/拾取模型 数据
     *  [{ title: '', position: [x,y,z]}, {...}], paths: [[x,y,z], [x,y,z]], [...]] }]
     * @param {Function} data.readyCallback 回调函数
     */
    mapS3M (data) {
      // 拾取颜色设置
      let _highlightColor = [255, 0, 0, 0.4]
      if (data.highlightColor) { _highlightColor = data.highlightColor }
      MAP_INSTANCE.setHighlightColor(new hmap.style.Color(_highlightColor[0], _highlightColor[1], _highlightColor[2], _highlightColor[3])) // 单体化  拾取-颜色
      // S3M图层
      MAP_S3M.osgbLayer = new hmap.layer.S3MLayer('S3M_LAYER', data.s3mUrl, {
        enableHashCode: data.pick // 可拾取 -> 单体化
      })
      MAP_INSTANCE.addLayer(MAP_S3M.osgbLayer, 10) // 一个整数，用以指定Layer在图层容器中的上下叠加顺序，值大的会压盖值小的图层，故显示在上面。不传或传null时，会自动赋值：该值取该图层容器中所有图层zIndex最大值+1。
      MAP_S3M.osgbLayer.onRootReady(() => {
        // 标识拾取事件
        if (data.pick) { MAP_S3M.pickEvent = true }
        // 标签/拾取模型数据 处理
        if (data.list && data.list.length > 0) {
          // labels
          if (data.labelOptions) {
            MAP_S3M.labelLayer = new hmap.layer.VectorLayer('VECTOR_S3M_LABEL', { isRTE: true })
            MAP_INSTANCE.addLayer(MAP_S3M.labelLayer)
            this.mapVectorMarker(MAP_S3M.labelLayer, data.list, data.labelOptions)
          }
          // pick polygons
          if (data.pick) {
            MAP_S3M.drawLayer = new hmap.layer.VectorLayer('VECTOR_S3M_POLYGON', { enableHashCode: true, isRTE: true, opacity: 0.4 })
            MAP_INSTANCE.addLayer(MAP_S3M.drawLayer)
            const features = []
            data.list.map(item => {
              const points = []
              if (item.paths && item.paths.length > 0) {
                item.paths.map(sitem => {
                  points.push(new hmap.geom.Point(this.mapGetCoordinate(sitem)))
                })
              }
              const polygon = new hmap.geom.Polygon([new hmap.geom.LinearRing(points)])
              features.push(new hmap.feature.Vector(polygon, item)) // attribute
            })
            MAP_S3M.drawLayer.addFeatures(features)
            MAP_S3M.drawLayer.setOpacity(0)
          }
        }
        // 回调函数
        if (data.readyCallback) {
          data.readyCallback()
        }
      })
    },
    // s3m三维地图拾取
    mapS3MPick (event) {
      const mapPixel = event.mapPixel
      const results = MAP_INSTANCE.detectFeaturesAtPixel(mapPixel, ['S3M_LAYER'])
      if (!results || results.length < 1) { return false }
      const coord = results[0].intersectCoordinate
      console.log('三维坐标：', coord.toArray())
      const intersectPoint = new hmap.geom.Point(coord)
      const features = MAP_S3M.drawLayer?.getAllFeatures() || []
      for (let i = features.length - 1; i >= 0; i--) {
        if (features[i].getGeometry().intersectsGeometry(intersectPoint)) {
          const attribute = features[i].getAttributes()
          // attribute.hasOwnProperty('minHeight') （foo.hasOwnProperty(“bar”) 应该替换为 Object.prototype.hasOwnProperty.call(foo, “bar”)）
          if (attribute && Object.prototype.hasOwnProperty.call(attribute, 'minHeight')) {
            const minHeight = attribute.minHeight
            const maxHeight = attribute.maxHeight
            if (minHeight <= coord._z && maxHeight >= coord._z) {
              console.log('S3M 单体化底面要素-分层分户：', features[i])
              MAP_S3M.osgbLayer.setHighlightFromGeometry(features[i].getGeometry(), minHeight, maxHeight) // 分层分户
              // console.log(coord, features[i])
              this.eventDataHandler({
                type: 'highlightS3M',
                eventType: 'click',
                lnglat: [event.lonlat._x, event.lonlat._y],
                data: attribute
              }, event)
              return
            }
          } else {
            console.log('S3M 单体化底面要素：', features[i])
            MAP_S3M.osgbLayer.setHighlightFromGeometry(features[i].getGeometry()) // 整个模型的高亮
            // console.log(coord, features[i])
            this.eventDataHandler({
              type: 'highlightS3M',
              eventType: 'click',
              lnglat: [event.lonlat._x, event.lonlat._y],
              data: attribute
            }, event)
            return
          }
        }
      }
      // LAYER_S3M.osgbLayer.setHighlightFromGeometry()
    },
    /**
     * [000001] 地图标记详情
     * @param {Object} data 数据
     */
    mapMarkerDetail (data) {
    },
    /**
     * [000010] 标记
     * @param {Object} data 数据
     * @param {Nmuber} data.level 级别，|| MAP_DEFAULT_LEVEL
     * @param {String} data.layerName 矢量图层名称
     * @param {Boolean} data.layerNoClear 不清除layerName数据（即默认清除layerName数据）
     * @param {Boolean} data.setHeight 如果是三维地图，是否需要设置高程，默认为false
     * @param {Object} data.labelOptions {icon: {}, textSymbol: {}} 标签配置数据 (为null则不用icon/textSymbol, 启用默认icon/textSymbol则为{})
     * @param {Function} data.click 点击回调函数
     * @param {Array} data.list 标记数据
     *  [{ title: '', position: [x,y,z]}, {...}], ... }]
     */
    mapMarkers (data) {
      // console.log('>>>>>>>>>> mapMarkers：', data)
      const _layerObj = this.mapLayerHandler(1, data) // 1 vector
      if (!_layerObj) return false
      this.mapVectorMarker(_layerObj.layer, data.list, data.labelOptions, data.click)
    },
    /**
     * Vector图层 标记
     * @param {Object} layer 图层
     * @param {Array} data.list 标签/拾取模型 数据
     *  [{ title: '', position: [x,y,z]}, {...}], paths: [[x,y,z], [x,y,z]], [...]] }]
     * @param {Object} labelOptions icon & textSymbol 标签配置数据 (为null则不用icon/textSymbol, 启用默认icon/textSymbol则为{})
     * @param {Function} _click 点击回调函数
     */
    mapVectorMarker (layer, list, labelOptions, _click) {
      const features = []
      const _markerSymbols = []
      if (labelOptions?.icon) {
        _markerSymbols.push(new hmap.style.Icon(Object.assign({
          imgSrc: './static/images/map/map_building.png',
          anchor: [0.5, 0.9], // 锚点位置。eg：默认将锚点定为图标的中心点，即[0.5,0.5]。图标的左上角为[0,0],右下角为[1,1]。单位为1。
          size: new hmap.basetype.Size(60, 72)
        }, labelOptions.icon)))
      }
      list.map(item => {
        const title = item.title ?? ' '
        const _coord = this.mapGetCoordinate(item.position)
        if (_coord) {
          const feature = new hmap.feature.Vector(new hmap.geom.Point(_coord))
          const _textSymbols = []
          if (labelOptions?.textSymbol) {
            _textSymbols.push(new hmap.style.TextSymbol(Object.assign({
              text: title,
              fontColor: new hmap.style.Color(255, 142, 1, 1),
              fontSize: 20,
              fontWeight: 'bold',
              haloWidth: 1,
              haloColor: new hmap.style.Color(255, 255, 255, 1),
              offset: new hmap.basetype.Offset(0, -80, 0),
              rowTextCount: 10
            }, labelOptions.textSymbol)))
          }
          feature.setStyle(new hmap.style.Style({
            markerSymbols: _markerSymbols,
            textSymbols: _textSymbols
          }))
          if (_click) {
            feature.onClick((event) => {
              // event.feature 可以取到要素本身
              _click(event, item)
            })
          }
          // feature.setAttributes({name:'卡口', age:14})
          features.push(feature)
        }
      })
      layer.addFeatures(features)
    },
    /**
     * [000011] OverlayLayer 标记 html (MapMarker)
     * @param {Object} data 数据
     * @param {Nmuber} data.level 级别，|| MAP_DEFAULT_LEVEL
     * @param {String} data.layerName 矢量图层名称
     * @param {Boolean} data.layerNoClear 不清除layerName数据（即默认清除layerName数据）
     * @param {String} data.component 组件
     * @param {Boolean} data.setHeight 如果是三维地图，是否需要设置高程，默认为false
     * @param {Array} data.list 标记数据
     *  data.list[n].position=[x, y, z]
     */
    mapMarkersOverlay (data) {
      const _layerObj = this.mapLayerHandler(2, data) // 2 overlay
      if (!_layerObj) return false
      data.list && data.list.map(item => {
        const panelDom = new MyMapMarker({
          data: {
            component: data.component,
            data: item
          },
          methods: {
          }
        })
        const simplePopup = new hmap.overlay.SimplePopup({
          location: this.mapGetCoordinate(item.position, data.setHeight),
          // editable: true,
          element: panelDom.$mount().$el
        })
        _layerObj.layer.addOverlay(simplePopup)
        // 将Marker实例根据图层放入容器
        _layerObj.doms.push(panelDom)
      })
      // MAP_LAYERS[data.layerName] = _layerObj
    },
    /**
     * [000020] 多边形
     * @param {Object} config 数据
     */
    mapPolygons (config) {
      if (!config.layerName) {
        console.log('地图层级名称不存在，则不允许地图任何操作')
        return
      }
      if (!MAP_LAYERS[config.layerName]) { // 如果组件层级不存在
        MAP_LAYERS[config.layerName] =  new hmap.layer.VectorLayer(config.layerName);
        MAP_INSTANCE.addLayer(MAP_LAYERS[config.layerName])
      }
      const {data} = config // 定义的数据
      const vectorLayer = MAP_LAYERS[config.layerName]
      const pointsArr = data.pointsArr
      const tempArr = []
      pointsArr.forEach(element => {
        tempArr.push(new hmap.geom.Point(new hmap.basetype.Coordinate(...element)),)
      });
      const ring = new hmap.geom.LinearRing(tempArr)
      //构造岛洞的面几何体
      const polygon = new hmap.geom.Polygon([ring]);
      const polygonStyle = data.polygonStyle || new hmap.style.Style({
        fillSymbols: [new hmap.style.ColorFill(new hmap.style.Color(0, 255, 0, 0.6))],
      });
      /* //构造线几何体
      const ring = new hmap.geom.LinearRing([
        new hmap.geom.Point(new hmap.basetype.Coordinate(113.228348, 25.875742)),
        new hmap.geom.Point(new hmap.basetype.Coordinate(113.238348, 25.875742)),
        new hmap.geom.Point(new hmap.basetype.Coordinate(113.238348, 25.865742)),
        new hmap.geom.Point(new hmap.basetype.Coordinate(113.228348, 25.865742)),
      ]);
      //构造岛洞的面几何体
      const polygon = new hmap.geom.Polygon([ring]);
      //线样式
      const polygonStyle = new hmap.style.Style({
        fillSymbols: [new hmap.style.ColorFill(new hmap.style.Color(0, 255, 0, 0.6))],
      });  */
      //创建面要素
      let polyFeature = new hmap.feature.Vector(polygon, null, polygonStyle);
      //添加到图层
      vectorLayer.addFeature(polyFeature);
    },
    /**
     * [000030] 折线
     * @param {Object} data 数据
     */
    mapPolylines (config) {
      if (!config.layerName) {
        console.log('地图层级名称不存在，则不允许地图任何操作')
        return
      }
      if (!MAP_LAYERS[config.layerName]) { // 如果组件层级不存在
        MAP_LAYERS[config.layerName] =  new hmap.layer.VectorLayer(config.layerName);
        MAP_INSTANCE.addLayer(MAP_LAYERS[config.layerName])
      }
      const {data} = config // 定义的数据
      const vectorLayer = MAP_LAYERS[config.layerName]
      const pointsArr = data.pointsArr
      const tempArr = []
      pointsArr.forEach(element => {
        tempArr.push(new hmap.geom.Point(new hmap.basetype.Coordinate(...element)),)
      });
      const line = new hmap.geom.Line(tempArr)
      //默认 线样式
      const lineSymbol = new hmap.style.LineSymbol({
        width: 2,
        color: new hmap.style.Color(250, 124, 40, 1),
      });


      const defaultLineStyle = new hmap.style.Style({ lineSymbols: [lineSymbol] });
      const lineStyle = data.lineStyle || defaultLineStyle
      //创建线要素
      let lineFeature = new hmap.feature.Vector(line, null, lineStyle);
    /* 
      //构造线几何体
      const line = new hmap.geom.Line([
        new hmap.geom.Point(new hmap.basetype.Coordinate(120.13636, 30.2521)),
        new hmap.geom.Point(new hmap.basetype.Coordinate(120.13756, 30.25245)),
        new hmap.geom.Point(new hmap.basetype.Coordinate(120.13825, 30.25184)),
        new hmap.geom.Point(new hmap.basetype.Coordinate(120.13879, 30.25189)),
        new hmap.geom.Point(new hmap.basetype.Coordinate(120.13909, 30.25144)),
        new hmap.geom.Point(new hmap.basetype.Coordinate(120.13962, 30.25154)),
        new hmap.geom.Point(new hmap.basetype.Coordinate(120.14003, 30.25116)),
        new hmap.geom.Point(new hmap.basetype.Coordinate(120.14076, 30.25137)),
        new hmap.geom.Point(new hmap.basetype.Coordinate(120.14132, 30.2532)),
        new hmap.geom.Point(new hmap.basetype.Coordinate(120.14082, 30.25339)),
        new hmap.geom.Point(new hmap.basetype.Coordinate(120.1413, 30.25498)),
        new hmap.geom.Point(new hmap.basetype.Coordinate(120.14205, 30.2553)),
        new hmap.geom.Point(new hmap.basetype.Coordinate(120.14194, 30.25648)),
        new hmap.geom.Point(new hmap.basetype.Coordinate(120.14297, 30.25601)),
        new hmap.geom.Point(new hmap.basetype.Coordinate(120.14428, 30.25588)),
    ]);
    //线样式
    const lineSymbol = new hmap.style.LineSymbol({
        width: 2,
        color: new hmap.style.Color(250, 124, 40, 1),
    });
    const lineStyle = new hmap.style.Style({ lineSymbols: [lineSymbol] });
    //创建线要素
    let lineFeature = new hmap.feature.Vector(line, null, lineStyle);
    */
    
    //添加到图层
    vectorLayer.addFeature(lineFeature);
    },
    /**
     * [001010] 聚合层
     * @param {Object} data 数据
     */
    mapLayerCluster (data) {
    },
    /**
     * [002010] 热力图
     * @param {Object} data 数据
     * @param {Nmuber} data.level 级别，|| MAP_DEFAULT_LEVEL
     * @param {Array} data.list 数据
     *  [[{"coord":[120.14322240845,30.236064370321],"elevation":21}, {"coord":[120.14280555506,30.23633761213],"elevation":5},...]]
     */
    mapHeatmap (data) {
      console.log('>>>>>>>>>>mapHeatmap data：', data)
      const points = [].concat.apply([], data.list.map(function (track) {
        return track.map(function (seg) {
          // 数据纠偏
          const x = seg.coord[0] - 0.01115
          const y = seg.coord[1] - 0.00335
          return [x, y].concat([1])
        })
      }))
      const option = {
        HMap: {
          roam: 'true'
        },
        coordinateSystem: 'HMap',
        visualMap: {
          show: false,
          top: 'top',
          min: 0,
          max: 5,
          seriesIndex: 0,
          calculable: true,
          inRange: {
            color: ['blue', 'blue', 'green', 'yellow', 'red']
          }
        },
        // title: {
        //   text: '热力图',
        //   left: 'center',
        //   textStyle: {
        //     color: '#111'
        //   }
        // },
        series: [{
          type: 'heatmap',
          coordinateSystem: 'HMap',
          data: points,
          pointSize: 5,
          blurSize: 6
        }]
      }
      var echartslayer = new EchartsLayer(MAP_INSTANCE)
      echartslayer.chart.setOption(option)
    },

    /**
     * 图层处理
     * @param {Nmuber} type 图层类型 1:Vector  2:Overlay
     * @param {Object} data 数据 { level: 2, layerName: '', layerNoClear: }
     */
    mapLayerHandler (type, data) {
      if (!data.layerName) {
        console.log('图层名称为空，', data)
        return null
      }
      let _layerObj = MAP_LAYERS[data.layerName] // 根据layerName从图层容器中获取图层
      if (_layerObj && !data.layerNoClear) {
        // 图层存在，且未指定不清空图层，则清空图层
        this.mapClearWithLayer(_layerObj)
      } else {
        // 图层不存在则新建图层
        _layerObj = {}
        _layerObj.type = type
        _layerObj.level = data.level ?? MAP_DEFAULT_LEVEL
        if (type === 1) { // Vector
          const _cfg = { isRTE: true }
          if (data.click) {
            // map enableInteractive() && layer  enableHashCode: true
            _cfg.enableHashCode = true
            MAP_INSTANCE.enableInteractive()
          }
          _layerObj.layer = new hmap.layer.VectorLayer(data.layerName, _cfg)
        } else if (type === 2) { // overlay
          _layerObj.layer = new hmap.layer.OverlayLayer(data.layerName)
          _layerObj.doms = []
        }
        MAP_INSTANCE.addLayer(_layerObj.layer)
        MAP_LAYERS[data.layerName] = _layerObj
      }
      return MAP_LAYERS[data.layerName]
    },

    /**
     * 清空图层 清空数据&doms
     * @param {Object} layerObj 图层对象{ type: 1, layer: layer, doms[], level: 2 } type 图层类型 1:Vector  2:Overlay
     */
    mapClearWithLayer (layerObj) {
      if (layerObj.type === 1) { // Vector
        layerObj && layerObj.layer && layerObj.layer.removeAllFeatures()
      } else if (layerObj.type === 2) { // overlay
        layerObj && layerObj.layer && layerObj.layer.removeAllOverlays()
      }
      if (layerObj.doms) {
        // 清除doms
        layerObj.doms.map((item) => {
          item.$destroy()
        })
        layerObj.doms = []
      }
    },

    /**
     * 清除地图
     * @param {Nmuber} clearLevel 清楚级别，默认为2(MAP_DEFAULT_LEVEL)
     */
    mapClear (clearLevel) {
      if (clearLevel === null || clearLevel === undefined) {
        // 默认清除级别
        clearLevel = MAP_DEFAULT_LEVEL
      }
      // clearLevel <= 0 不清除
      if (!MAP_INSTANCE || clearLevel <= 0) { return false }
      for (const i in MAP_LAYERS) {
        if (MAP_LAYERS[i].level <= clearLevel) {
          // 清除所有级别小于clearLevel的图层
          this.mapClearWithLayer(MAP_LAYERS[i])
        }
      }
    },

    /**
     * 获取Coordinate（自动调用坐标处理器）   **** 此函数的执行需要在三维地图 加载完成之后，不然计算不出来
     * @param {Array} position 数据 [x, y, z]
     * @param {Boolean} setHeight 如果是三维地图，是否需要设置高程，默认为false
     */
    mapGetCoordinate (position, setHeight = false) {
      let _coord = null
      if (position && position[0] > 0 && position[1] > 0) {
        // const _pst = this.mapCoordinateHandler([position])[0]
        this.mapCoordinateHandler([position])
        _coord = new hmap.basetype.Coordinate(position[0], position[1], position[2] ?? 0)
        if (setHeight) {
          // 获取指定坐标点位，在地图三维场景中的实际高程。当传入的坐标点经纬度，不在地图范围内时，会返回null
          const _z = MAP_INSTANCE.getHeightByCoord(_coord)
          if (_z != null) {
            _coord.setOrdinate('Z', _z)
          }
        }
      }
      return _coord
    },
    /**
     * 坐标处理器 --->>> 如果需要转换坐标则可在这里进行统一转换
     * @param {Array} positions 坐标 [[120.14280555506, 30.23633761213, 0], ...]
     */
    mapCoordinateHandler (positions) {
      // positions.map(item => {
      //   // 转换
      //   item = [...item]
      // })
    }
  }
}
